package com.example.nick.bodyapplication.widget

import android.app.ActionBar
import android.app.AlertDialog
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import com.example.nick.bodyapplication.R
import kotlinx.coroutines.*

class WaitingDialog(context: Context, var timeout: Long) : AlertDialog(context), CoroutineScope by MainScope() {

    var showing: Boolean = false
    var ajob: Job? = null

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.my_dialog_progress, null, false)
        setView(view)
        setOnDismissListener {
            showing = false
            ajob?.cancel()
        }
    }

    fun showWaiting() {
        if (showing) {
            resetJob()
            return
        }
        resetJob()
        showing = true
        show()
        window?.setLayout(500, ActionBar.LayoutParams.WRAP_CONTENT)
    }

    private fun resetJob() {
        ajob?.cancel()
        ajob = launch(Dispatchers.IO) {
            Log.i("dialog", "showMyProgressDialog 000")
            delay(timeout)
            if (showing) {
                Log.e("dialog", "showMyProgressDialog myProgressDialog dismiss")
                dismiss()
            }
            Log.i("dialog", "showMyProgressDialog 111")
        }
    }
}